package leetcode.problems;

/**
 * _0327ReverseInteger
 * 反转数字
 * Created by gmwang on 2018/3/23
 */
public class _0327ReverseInteger {
    /**
     * Given a 32-bit signed integer, reverse digits of an integer.
     * Example 1:
     * <p>
     * Input: 123
     * Output:  321
     * Example 2:
     * <p>
     * Input: -123
     * Output: -321
     * Example 3:
     * <p>
     * Input: 120
     * Output: 21
     * Note:
     * Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range.
     * For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
     * <p>
     * 给定一个32位有符号整数，整数的反向数字。
     * <p>
     * 假设我们正在处理一个只能在32位带符号整数范围内保存整数的环境。
     * 为了解决这个问题，假设当反整数溢出时，函数返回0。
     */
    public static int reverse(int x) {
        int carry = 0;
        int length = 0;
        String s = x + "";
        if (s.contains("-")) {
            length = s.length() - 1;
        } else {
            length = s.length();
        }
        double f = Math.pow(10, length - 1);
        while (x != 0) {
            carry += x % 10 * f;
            f /= 10;
            x = x / 10;
        }
        return carry;
    }
    public static int reverseAn(int x) {
        int sign = x < 0 ? -1 : 1;
        x = Math.abs(x);
        int res = 0;
        while (x > 0) {
            if (Integer.MAX_VALUE / 10 < res || (Integer.MAX_VALUE - x % 10) < res * 10) {
                return 0;
            }
            res = res * 10 + x % 10;
            x /= 10;
        }
        return sign * res;
    }
    public static void main(String[] args) {
        System.out.println(reverseAn(120));
//        System.out.println(-12%10);
//        System.out.println(-123/10);
    }
}
